package com.sxfq.loansupermarket.backsystem.modular.refunds.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.SearchPaymentTotalInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.service.IPaymentTotalService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/paymentTotal")
public class PaymentTotalController extends BaseController {
    @Autowired
    IPaymentTotalService service;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/balance/";

    /**
     * 跳转到预约客户管理页面
     */
    @RequestMapping(value = "")
    public String recharge(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("sttleAccountsTime", ShiroKit.getUser().getSttleAccountsTime());
        return PREFIX + "payment_total.html";
    }

    @RequestMapping("/getPaymentTotalReport")
    @ResponseBody
    public List<Map<String, Object>> getPaymentTotalReport(SearchPaymentTotalInfo searchInfo, String reach) {
        return service.getList(searchInfo,reach);
    }

    //导出
    @RequestMapping(value = "/paymentTableExport")
    public void paymentTableExport(@Valid SearchPaymentTotalInfo info, HttpServletResponse response) {
        try {
            List<LinkedHashMap<String, Object>> list = service.paymentTableExport(info,info.getReach());
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 27; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell;
            for (int i = 0;  i< list.size(); i++) {
                Map<String, Object> map = list.get(i);
                int a=0;
                for (String key : map.keySet()) {
                    cell = row.createCell(a);
                    cell.setCellValue(key);
                    cell.setCellStyle(style);
                    a=a+1;
                }
            }
            // 填充数据
            for (int i = 0;  i< list.size(); i++) {
                Map<String, Object> map = list.get(i);
                row = sheet.createRow(i + 1);
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= map.size(); j++) {
                    row.createCell(j).setCellStyle(style);
                }
                int a=0;
                for (String key : map.keySet()) {
                    if(ShiroKit.getUser().getPhonePrivilegesexp()!=1 && "电话".equals(key)) {
                        row.getCell(a).setCellValue("无");
                    }else{
                        row.getCell(a).setCellValue(map.get(key).toString());
                    }
                    a=a+1;
                }
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/sumBorrowAmount")
    @ResponseBody
    public HashMap sumBorrowAmount(@RequestParam(required = false) String reach,
                                   @RequestParam(required = false) String checkoutMethod,
                                   @RequestParam(required = false) String fieldTc,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String customerStatus,
                                   @RequestParam(required = false) String endTime,@RequestParam String abbreviation) {
        String sql = " (select sum(t.borrowAmount_sum) as borrowAmount_sum from (select t1.actual_account_balance as borrowAmount_sum " +
                " from " + abbreviation + "recharge_info" + " t1 left join " + abbreviation + "customer_info" + " t2 on t1.customer_id=t2.id " +
                " left join " + ShiroKit.getUser().getDeal_info() + " t3 on t1.deal_id=t3.id where 1=1" +
                " and t1.isEarnes!=3 and !(t1.isEarnes=2 and t1.section_performance=0 and t1.hospital_performance=0) ";
        if (StringUtil.isNotEmpty(reach)) {
            sql += "  and (t2.customer_name like CONCAT('%','" + reach + "','%') or t2.customer_phone like CONCAT('%','" + reach + "','%') or " +
                    " t2.wechat_number like CONCAT('%','" + reach + "','%') or t2.medical_record_number like CONCAT('%','" + reach + "','%') " +
                    " or t2.szm like CONCAT('%','" + reach + "','%'))";
        }
        if (StringUtil.isNotEmpty(checkoutMethod)) {
            sql += " and t1.checkout_method = '" + checkoutMethod + "'";
        }
        if (StringUtil.isNotEmpty(fieldTc)) {
            sql += " and (t3.tc_name = '" + fieldTc + "' or t1.tc_name='"+ fieldTc +"') ";
        }
        if (StringUtil.isNotEmpty(customerStatus)) {
            sql += " and t2.customer_status = '" + customerStatus + "'";
        }
        if (StringUtil.isNotEmpty(startTime)) {
            sql += " and t1.recharge_time >= '" + startTime + "'";
        }
        if (StringUtil.isNotEmpty(endTime)) {
            sql += " and t1.recharge_time <= '" + endTime + "'";
        }
        sql += " group by t1.id) t) ";
        Map<String, Object> result = sqlMapper.selectOne(sql.toString());
        HashMap map = new HashMap();
        if (result != null) {
            map.put("borrowAmount_sum", result.get("borrowAmount_sum"));
        } else {
            map.put("borrowAmount_sum", "0");
        }
        return map;
    }
}
